<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置参数！"
        type="warning"
        show-icon
        :closable="false">
      </el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="cateKeys"
            :options="cateList"
            @change="cateCascaderChange"
            :props="cateProps"
            clearable>
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button @click="addCatedialog = true" :disabled="isBtnDisabled" size="mini" type="primary">添加参数</el-button>
          <el-table
            :data="manyTableData"
            border
            stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="tagClose(index, scope.row)" closable v-for="(item, index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row.attr_id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button @click="del(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button @click="addCatedialog = true" :disabled="isBtnDisabled" size="mini" type="primary">添加属性</el-button>
          <el-table
            :data="onlyTableData"
            border
            stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag @close="tagClose(index, scope.row)" closable v-for="(item, index) in scope.row.attr_vals" :key="index">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button @click="showEditDialog(scope.row.attr_id)" size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button @click="del(scope.row.attr_id)" size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleDialog"
      :visible.sync="addCatedialog"
      width="50%"
      @close="addDialogClose">
      <el-form :model="addCateForm" :rules="addCateForRrules" ref="addCateFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleDialog + '名称'" prop="attr_name">
          <el-input v-model="addCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCatedialog = false">取 消</el-button>
        <el-button type="primary" @click="addSureDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog
      :title="'修改' + titleDialog"
      :visible.sync="editCatedialog"
      width="50%"
      @close="editDialogClose">
      <el-form :model="editCateForm" :rules="addCateForRrules" ref="editCateFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleDialog + '名称'" prop="attr_name">
          <el-input v-model="editCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCatedialog = false">取 消</el-button>
        <el-button type="primary" @click="editSureDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      cateKeys: [],
      activeTabName: 'many',
      // 动态参数
      manyTableData: [],
      // 静态属性
      onlyTableData: [],
      addCatedialog: false,
      addCateForm: {},
      addCateForRrules: {
        attr_name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      editCatedialog: false,
      editCateForm: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 级联选择框改变时触发
    cateCascaderChange() {
      // 判断是否选择的三级分类
      this.getCateTherrlist()
    },
    // 标签页切换时触发
    handleTabClick() {
      this.getCateTherrlist()
    },
    // 获取三级参数列表
    async getCateTherrlist() {
      if (this.cateKeys.length !== 3) {
        this.cateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateThreeId}/attributes`, { params: { sel: this.activeTabName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeTabName === 'many') this.manyTableData = res.data
      this.onlyTableData = res.data
    },
    // 重置添加表单
    addDialogClose() {
      this.$refs.addCateFormRef.resetFields()
    },
    // 重置修改表单
    editDialogClose() {
      this.$refs.editCateFormRef.resetFields()
    },
    // 点击添加确定按钮
    addSureDialog() {
      this.$refs.addCateFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.post(`categories/${this.cateThreeId}/attributes`, { attr_name: this.addCateForm.attr_name, attr_sel: this.activeTabName })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateTherrlist()
        this.addCatedialog = false
      })
    },
    // 点击修改确定按钮
    editSureDialog() {
      this.$refs.editCateFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put(`categories/${this.cateThreeId}/attributes/${this.editCateForm.attr_id}`, { attr_name: this.editCateForm.attr_name, attr_sel: this.activeTabName })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getCateTherrlist()
        this.editCatedialog = false
      })
    },
    // 点击修改按钮
    async showEditDialog(attrId) {
      this.editCatedialog = true
      const { data: res } = await this.$http.get(`categories/${this.cateThreeId}/attributes/${attrId}`, { params: { attr_sel: this.activeTabName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editCateForm = res.data
    },
    // 点击删除按钮
    async del(attrId) {
      const confirmRestul = await this.$confirm(`此操作将永久删除该${this.titleDialog}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击确定按钮confirm
      // 点击取消cancel
      if (confirmRestul === 'cancel') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateThreeId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getCateTherrlist()
    },
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.savaAttrvals(row)
    },
    // 将改变的分类保存到数据库
    async savaAttrvals(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateThreeId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // 关闭tag标签删除标签
    tagClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.savaAttrvals(row)
    },
    showInput(row) {
      row.inputVisible = true
      // 自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 控制添加按钮是否启用
    isBtnDisabled() {
      if (this.cateKeys.length === 3) return false
      return true
    },
    // 获取三级分类的id
    cateThreeId() {
      if (this.cateKeys.length === 3) {
        return this.cateKeys[2]
      }
      return null
    },
    // 对话框的标题
    titleDialog() {
      if (this.activeTabName === 'only') return '属性'
      return '参数'
    }
  }
}
</script>

<style lang="less" scoped>
.el-row{
  margin: 15px 0;
}
.el-tag{
  margin: 5px;
}
.input-new-tag{
  width: 120px;
}
</style>
